<?php

/**
 * blog actions.
 *
 * @package    lezgro
 * @subpackage blog
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class imageActions extends sfActions
{
    
  public function executeAjaxUploadImage(sfWebRequest $request) {
        //$this->forward404Unless($request->isXmlHttpRequest());
        $this->forward404Unless($this->getUser()->isAuthenticated());
        sfConfig::set('sf_web_debug', false);
        $response = array();
        try {
            $files = $request->getFiles();
            $validator = new CustomValidatorFile(array(
                        'required' => false,
                        'mime_types' => 'images',
                        'temp' => true
                    ));


            $file = $validator->clean($files['upload']);
            $uploaded_file['uri'] = $file->save();
            $uploaded_file['filepath'] = str_replace('\\', '/', str_replace(sfConfig::get('sf_upload_dir'), '/uploads', $file->getSavedName()));

            $big_size = sfConfig::get('app_image_big_size', 500);
            $quality = sfConfig::get('app_image_quality', 80);
             $image_uri_temp = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . $uploaded_file['uri'];
            $image_uri_b = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . 'images'   . DIRECTORY_SEPARATOR .  $uploaded_file['uri'];

            $sf_image = new sfImage($image_uri_temp,'image/jpg');
            if (($sf_image->getWidth() > $big_size) || ($sf_image->getHeight() > $big_size))
                $sf_image->thumbnail($big_size, $big_size, 'scale');
            $sf_image->setQuality($quality);
            $sf_image->saveAs($image_uri_b);
            sfProjectConfiguration::getActive()->loadHelpers('Asset');
            $uploaded_file['filepath'] = image_path('/uploads/images/' . $uploaded_file['uri'], true);
            
            $response['uploaded_file'] = $uploaded_file;

                $image = new Image();
                $image->setUri($uploaded_file['uri']);
                $image->setUploaderId($this->getUser()->getUserProfile()->getId());
                $image->save();

                $response['image_id'] = $image->getId();

        } catch (Exception $e) {
            sfProjectConfiguration::getActive()->loadHelpers('I18N');
            $response['errors'] = array(__('Ошибка загрузки') => $e->getMessage());
        }
        return $this->renderText(json_encode($response));
    }

}
